﻿using System.IO;
using System.Text;

namespace CommonUtils
{
    /// <summary>
    /// 文本编码解码工具
    /// </summary>
    public static class TextEncode
    {
        /// <summary>
        /// 文本编码
        /// </summary>
        public static byte[] Encode(this string text, Encoding encoding = null)
        {
            var bytes = encoding.Null2utf8().GetBytes(text);
            //Encoding.UTF8没有加Bom，这里判断Encodings.UTF8Bom强制加上了
            if (encoding == TextEncoding.UTF8Bom)
                //0xEF, 0xBB, 0xBF 239, 187, 191
                bytes = TextEncoding.UTF8BomBytes.Append(bytes);
            return bytes;
        }

        /// <summary>
        /// 文本编码
        /// </summary>
        public static byte[] ToBytes(this string text, Encoding encoding = null)
        => text.Encode(encoding);

        /// <summary>
        /// 文本编码
        /// </summary>
        public static byte[] GetBytes(this string text, Encoding encoding = null)
        => text.Encode(encoding);

        /// <summary>
        /// 字节文本解码
        /// </summary>
        public static string Decode(this byte[] bytes, Encoding encoding = null)
        {
            //这里判断Encodings.UTF8Bom强制解除bom
            if (encoding == TextEncoding.UTF8Bom && bytes.Cut(3).EqualValue(TextEncoding.UTF8BomBytes))
                bytes = bytes.CutAt(3);
            return encoding.Null2utf8().GetString(bytes);
        }

        /// <summary>
        /// 字节文本解码
        /// </summary>
        public static string ToText(this byte[] bytes, Encoding encoding = null)
        => bytes.Decode(encoding);

        /// <summary>
        /// 字节文本解码
        /// </summary>
        public static string GetText(this byte[] bytes, Encoding encoding = null)
        => bytes.Decode(encoding);

        /// <summary>
        /// 文本二次解码
        /// </summary>
        public static string Redecode(this string text, Encoding encodeEncoding, Encoding redecodeEncoding)
        => text.Encode(encodeEncoding).Decode(redecodeEncoding);

        /// <summary>
        /// 文本Utf8编码
        /// </summary>
        public static byte[] Utf8Encode(this string text)
        => Encoding.UTF8.GetBytes(text);

        /// <summary>
        /// 字节Utf8文本解码
        /// </summary>
        public static string Utf8Decode(this byte[] bytes)
        => Encoding.UTF8.GetString(bytes);

        /// <summary>
        /// 将string转成stream
        /// </summary>
        public static Stream GetStream(this string text, Encoding encoding = null)
        {
            var stream = new MemoryStream();
            stream.Load(text, encoding, false);
            stream.Seek();
            return stream;
        }
    }
}
